import json
import re
import os
import glob
from typing import Dict, List
from pathlib import Path

class AdvancedHexBinConverter:
    def __init__(self, segment_size=272):
        self.segment_size = segment_size
        self.hex_pattern = re.compile(r'[0-9A-Fa-f]{2}')

    def __validate_hex(self, hex_str):
        hex_bytes = []
        for match in self.hex_pattern.finditer(hex_str):
            try:
                val = int(match.group(), 16)
                hex_bytes.append(val)
            except ValueError:
                continue
        return bytes(hex_bytes)
    
    def _process_entry(self, hex_list):
        merged = ''.join([h.replace(' ', '') for h in hex_list])
        bin_data = self.__validate_hex(merged)

        data_len = len(bin_data)
        if data_len > self.segment_size:
            return bin_data[:self.segment_size]
        elif data_len < self.segment_size:
            return bin_data + bytes([0] * (self.segment_size - data_len))
        return bin_data
    
    def convert_file(self, input_json, output_bin=None):
        """转换单个 JSON 文件到 BIN 文件"""
        if output_bin is None:
            output_bin = input_json.replace('.json', '.bin')
        
        with open(input_json, 'r') as f:
            data: Dict[str, List[str]] = json.load(f)
        
        total = len(data)
        success = 0

        with open(output_bin, 'wb') as bin_file:
            for key, hex_list in data.items():
                try:
                    segment = self._process_entry(hex_list)
                    bin_file.write(segment)
                    success += 1
                except Exception as e:
                    print(f"记录 {key} 处理失败: {str(e)}")
                    continue
        
        print(f"转换统计 | 文件: {os.path.basename(input_json)} | 总数: {total} | 成功: {success} | 失败: {total-success}")
        return (total, success, total-success)
    
    def convert_directory(self, directory_path):
        """转换目录中的所有 MCTP JSON 文件"""
        directory_path = Path(directory_path)
        if not directory_path.exists():
            print(f"错误: 目录不存在: {directory_path}")
            return
        
        # 查找所有以 _mctp.json 结尾的文件
        json_files = list(directory_path.rglob('*_mctp.json'))
        
        if not json_files:
            print(f"在目录 {directory_path} 中未找到 *_mctp.json 文件")
            return
        
        print(f"找到 {len(json_files)} 个 MCTP JSON 文件")
        
        total_records = 0
        total_success = 0
        total_fail = 0
        
        for json_file in json_files:
            print(f"\n处理文件: {json_file}")
            
            # 生成对应的 bin 文件路径
            bin_file = json_file.with_suffix('.bin')
            
            # 转换文件
            records, success, fail = self.convert_file(str(json_file), str(bin_file))
            
            total_records += records
            total_success += success
            total_fail += fail
            
            # 验证生成的文件
            expected_size = success * self.segment_size
            actual_size = os.path.getsize(bin_file)
            
            if actual_size != expected_size:
                print(f"警告: 文件 {bin_file.name} 完整性校验失败: 预期 {expected_size} 字节, 实际 {actual_size} 字节")
            else:
                print(f"文件 {bin_file.name} 验证通过: {actual_size} 字节")
        
        print(f"\n总转换统计 | 文件数: {len(json_files)} | 记录总数: {total_records} | 成功: {total_success} | 失败: {total_fail}")

if __name__ == "__main__":
    converter = AdvancedHexBinConverter()
    
    # 设置要处理的目录路径
    target_directory = os.getcwd()
    
    try:
        # 处理目录中的所有 MCTP JSON 文件
        converter.convert_directory(target_directory)
        print("所有文件处理完成!")
    
    except Exception as e:
        print(f"处理过程中发生错误: {str(e)}")
        import traceback
        traceback.print_exc()